package com.wasion.pwportable.activity;

import java.lang.reflect.Constructor;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.wasion.core.config.Config;
import com.wasion.core.util.PackageUtil;
import com.wasion.core.util.StringUtil;
import com.wasion.pwportable.R;
import com.wasion.pwportable.handler.USBDeviceHandler;
import com.wasion.pwportable.jsi.JSIHelper;
import com.wasion.pwportable.protocol.Protocol;
import com.wasion.pwportable.usb.F232DeviceManager;

/**
 * 
 * @ClassName: PwPortableActivity
 * @Description: 配网便携施工及维护系统入口Activity
 * @author 高意
 * @date 2014年7月22日 下午5:19:17
 * 
 */
@SuppressLint("SetJavaScriptEnabled")
public class PwPortableActivity extends Activity {

	// 日志标签
	private static final String LOG_TAG = Config.LOG_TAG_GLOBOL;

	private static final String APP_CACAHE_DIRNAME = "/webcache";

	// 进度条最小值和最大值
	public static final int PROGRESS_MIN = 0;
	public static final int PROGRESS_MAX = 100;

	// 当前的进度
	public static int pro = 0;

	public ProgressDialog progressDialog;

	// 是否挂载设备
	private static boolean isUSBAttached = false;

	public static boolean isUSBAttached() {
		return isUSBAttached;
	}

	public static void setUSBAttached(boolean isUSBAttached) {
		PwPortableActivity.isUSBAttached = isUSBAttached;
	}

	// 主界面
	private static WebView mWebView = null;

	// 主Handler
	private static Handler handler;

	// FT232芯片扩展串口的设备管理器
	private F232DeviceManager usbDevice;

	private static BluetoothAdapter blueToothAdapter;

	static boolean IS_BLUE_TOOTH_CHANGED = false;

	public static WebView getWebView() {
		return mWebView;
	}

	public static Handler getHandler() {
		return handler;
	}

	public static BluetoothAdapter getBluetoothAdapter() {
		return blueToothAdapter;
	}

	protected void onCreate(Bundle savedInstanceState) {

		Log.i(LOG_TAG, "------------ onCreate ------------ "
				+ "Being creating Activity!");

		super.onCreate(savedInstanceState);

		usbDevice = F232DeviceManager.getInstance(getApplicationContext());
		IntentFilter filter = new IntentFilter();
		filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
		filter.setPriority(500);
		this.registerReceiver(mUsbPlugEvents, filter);

		// 检查设备是否支持蓝牙
		blueToothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (null == blueToothAdapter) {
			// 设备不支持蓝牙
			JSIHelper.showToast(this, "设备不支持蓝牙");
		}

		// 1.去除title
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// 2.去掉Activity上面的状态栏
		// getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		/*
		 * getWindow().setFlags(
		 * WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
		 * WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		 * getWindow().setSoftInputMode(
		 * WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
		 * WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		 */

		// 获取布局控件
		setContentView(R.layout.main_view);
		mWebView = (WebView) findViewById(R.id.webView);

		handler = new Handler();

		// webview的配置
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setSaveFormData(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setSupportZoom(false);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBlockNetworkImage(true);

		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT); // 设置
		// 开启 DOM storage API 功能
		webSettings.setDomStorageEnabled(true);
		// 开启 database storage API 功能
		webSettings.setDatabaseEnabled(true);
		String cacheDirPath = getFilesDir().getAbsolutePath()
				+ APP_CACAHE_DIRNAME;
		// 设置 Application Caches 缓存目录
		webSettings.setAppCachePath(cacheDirPath);
		// 开启 Application Caches 功能
		webSettings.setAppCacheEnabled(true);

		List<Class<?>> classes = PackageUtil
				.getClasses(Config.JAVASCRIPT_INTERFACE_CLASSES_STR);
		if (0 < classes.size()) {
			for (Class<?> c : classes) {
				// 获取类名
				String className = c.getName();
				className = className.substring(className.lastIndexOf(".") + 1);
				try {
					// 根据参数类型获取相应的构造函数
					Constructor<?> constructor = c
							.getConstructor(Context.class);

					mWebView.addJavascriptInterface(
							constructor.newInstance(this),
							className.toLowerCase());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		// int color = getResources().getColor(R.color.black_overlay);
		mWebView.setBackgroundColor(Color.parseColor("#A1E7FF")); // 设置背景色
		mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		mWebView.getBackground().setAlpha(100); // 设置填充透明度 范围：0-255
		mWebView.setVisibility(View.VISIBLE);

		Log.i(LOG_TAG, "------------ onCreate ------------ "
				+ "Loading the home page now!");
		// webview加载主页
		mWebView.loadUrl("file:///android_asset/www/index.html");

		/*
		 * Set<BluetoothDevice> devices = blueToothAdapter.getBondedDevices();
		 * Iterator<BluetoothDevice> iterator = devices.iterator();
		 * 
		 * while (iterator.hasNext()) { BluetoothDevice device =
		 * iterator.next(); System.out.println(device.getName());
		 * 
		 * if ("CT10".equalsIgnoreCase(device.getName().substring(0, 4))) {
		 * final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB"; UUID
		 * uuid = UUID.fromString(SPP_UUID); BluetoothSocket socket; try {
		 * socket = device.createRfcommSocketToServiceRecord(uuid);
		 * socket.connect(); } catch (IOException e) { e.printStackTrace(); }
		 * 
		 * } }
		 */

		// 设置WebViewClient
		mWebView.setWebViewClient(new WebViewClient() {

			// url拦截
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// 使用自己的WebView组件来响应Url加载事件，而不是使用默认浏览器器加载页面
				view.loadUrl(url);
				// 相应完成返回true
				return true;
			}

			// 页面开始加载
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				if (progressDialog == null) {
					progressDialog = new ProgressDialog(
							PwPortableActivity.this,
							R.style.ProgressDialog_Theme);
					/** 设置透明度 */
					Window window = progressDialog.getWindow();
					WindowManager.LayoutParams lp = window.getAttributes();
					lp.alpha = 0.7f;// 透明度
					lp.dimAmount = 0.8f;// 黑暗度
					window.setAttributes(lp);

					progressDialog.setMessage("数据加载中, 请稍候...");
					progressDialog.show();
					mWebView.setEnabled(false);// 当加载网页的时候将网页进行隐藏
				}
				super.onPageStarted(view, url, favicon);
			}

			// 页面加载完成
			public void onPageFinished(WebView view, String url) {
				if (progressDialog != null && progressDialog.isShowing()) {
					progressDialog.dismiss();
					progressDialog = null;
					mWebView.setEnabled(true);
				}
				mWebView.getSettings().setBlockNetworkImage(false);
				super.onPageFinished(view, url);
			}

			// WebView加载的所有资源url
			public void onLoadResource(WebView view, String url) {
				super.onLoadResource(view, url);
			}

			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
			}

		});

		/*
		 * 设置WebChromeClient
		 */
		mWebView.setWebChromeClient(new WebChromeClient() {

			// 处理javascript中的alert
			public boolean onJsAlert(WebView view, String url, String message,
					final JsResult result) {
				return super.onJsAlert(view, url, message, result);
			};

			// 处理javascript中的confirm
			public boolean onJsConfirm(WebView view, String url,
					String message, final JsResult result) {
				return super.onJsConfirm(view, url, message, result);
			};

			public boolean onJsPrompt(WebView view, String url, String message,
					String defaultValue, JsPromptResult result) {
				return super.onJsPrompt(view, url, message, defaultValue,
						result);
			}

			// 设置网页加载的进度条
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
			}

			// 设置程序的Title
			public void onReceivedTitle(WebView view, String title) {
				setTitle(title);
				super.onReceivedTitle(view, title);
			}

		});
	}

	// 上一次点击退出键的时间
	private static long LAST_TIME_OF_KEY_BACK = 0;

	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {

			if (mWebView.canGoBack() && event.getRepeatCount() == 0) {
				String url = mWebView.getUrl();
				if (-1 < url.indexOf("implement/")) {
					mWebView.loadUrl("javascript:onBackKey()");
					mWebView.stopLoading();
				} else {
					mWebView.goBack();
				}

				return true;
			} else {
				if ((System.currentTimeMillis() - LAST_TIME_OF_KEY_BACK) > 2000) {
					Toast.makeText(getApplicationContext(), "亲, 再按一次退出程序",
							Toast.LENGTH_SHORT).show();
					LAST_TIME_OF_KEY_BACK = System.currentTimeMillis();
				} else {
					finish();
					System.exit(0);
				}
				return true;
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {

		this.unregisterReceiver(mUsbPlugEvents);
		usbDevice.disconnect();
		super.onDestroy();
	}

	/**
	 * Hot plug for plug in solution This is workaround before android 4.2 .
	 * Because BroadcastReceiver can not receive ACTION_USB_DEVICE_ATTACHED
	 * broadcast
	 */
	@Override
	public void onResume() {
		super.onResume();

		Intent intent = this.getIntent();

		String action = intent.getAction();
		String hotplug = "android.intent.action.MAIN";

		if (hotplug.equals(action) && StringUtil.isEmpty(Protocol.SENDERID)) {

			USBDeviceHandler handler = new USBDeviceHandler(this);
			handler.getDeviceInfo();
		}
	}

	/**
	 * 主Activity配置USB_DEVICE_ATTACHED 广播接收器，接收USB设备拔插事件
	 */
	private BroadcastReceiver mUsbPlugEvents = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
				Toast.makeText(context, "设备已连接!", Toast.LENGTH_SHORT).show();
			} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
				usbDevice.disconnect();
				Protocol.SENDERID = "";
				Toast.makeText(context, "设备已拔出!", Toast.LENGTH_SHORT).show();
			}
		}
	};
}
